package xh.lumt.server;

/**
 * Created by Administrator on 2016/6/25.
 */

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import xh.lumt.util.Global;
import xh.lumt.util.HttpUtils;

import java.net.URLDecoder;
import java.util.HashSet;
import java.util.Set;

import static io.netty.handler.codec.http.HttpHeaders.Names.LOCATION;
import static io.netty.handler.codec.http.HttpResponseStatus.FOUND;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;


public class HttpServerInboundHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        FullHttpRequest request = (FullHttpRequest) msg;

        String uri = URLDecoder.decode(request.getUri(), Global.DefaultCharset.name());
        System.out.println("Uri:" + uri);


        if (uri.equals("/favicon.ico")) {
            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
            response.headers().set(LOCATION, "/statics/favicon.ico");
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
            return;
        }

        if (uri.length() == 0 || uri.equals("/")) {
            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
            response.headers().set(LOCATION, "/statics/html/lumt.htm");

            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
            return;
        }

        ByteBuf buf = request.content();
        System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));

        RequestProcessor processor = new RequestDispatcher().dispatch(request, ctx);

        if (processor == null) {
            FullHttpResponse response = HttpUtils._404();
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            FullHttpResponse response;
            try {
                response = processor.process();
            } catch (Exception e) {
                e.printStackTrace();
                response = HttpUtils._500();
            }

            if (response != null) {
                ctx.write(response);
                ctx.flush();
            }
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}